#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#include <stdexcept>
#include "GBConfig.h"

using namespace std;

GBConfig::GBConfig(std::string filename)
{
	int ret;
	this->filename = filename;
	ret = this->parse();
	if(ret < 0) {
		cerr << "error parsing " << this->filename << ": " << strerror(errno) << endl;
		throw invalid_argument("error parsing " + this->filename + ": " + strerror(errno));
	}
}

GBConfig::~GBConfig()
{
}

void GBConfig::setValue(const char *k, const char *v)
{
	hsh[k] = v;
}

std::string GBConfig::getValue(const char *k)
{
	return hsh[k];
}

int GBConfig::getIntValue(const char *k)
{
	std::string v = hsh[k];
	return atoi(v.c_str());
}

int GBConfig::parse()
{
	FILE *fp = fopen(this->filename.c_str(), "r");
	char buf[BUFSIZ];
	if(!fp) {
		return -1;
	}

	this->setValue("concurrency", "1");
	this->setValue("dbhost","localhost");
	this->setValue("dbuser","root");
	this->setValue("dbname","gamebrowser");

	while((fgets(buf, BUFSIZ, fp))) {
		char *value;
		if(*buf == '#') {
			continue;
		}

		if((value = strchr(buf, '='))) {
			char *tmp;
			*value = '\0';
			value++;
			if((tmp = strchr(value, '\r')) || (tmp = strchr(value, '\n'))) {
				*tmp = '\0';
			}
			this->setValue(buf, value);
		}
	}

	fclose(fp);
	return 0;
}
